<template>
  <div class="home">
    <v-row>
      <v-col md="4" cols="12">
        <v-text-field
          v-model="searchQuery"
          label="搜索电影"
          append-icon="mdi-magnify"
          clearable
          outlined
          dense
          dark
          hide-details
          color="primary"
          background-color="rgba(255, 255, 255, 0.05)"
          @keyup.enter="handleSearch"
          @click:append="handleSearch"
          :loading="searching"
        ></v-text-field>
      </v-col>
      <v-col md="8" cols="12" class="d-flex align-center">
        <v-select
          v-model="selectedCategory"
          :items="categories"
          label="电影类型"
          outlined
          dense
          dark
          class="mr-4"
        ></v-select>
        <v-select
          v-model="sortBy"
          :items="sortOptions"
          label="排序方式"
          outlined
          dense
          dark
          class="mr-4"
        ></v-select>
      </v-col>
    </v-row>

    <v-row>
      <v-col cols="12" md="3" sm="6"
             v-for="(item, index) in paginatedMovies" 
             :key="index"
             class="movie-col"
      >
        <movie-card :movie="item"/>
      </v-col>
    </v-row>

    <v-row justify="center" class="mt-6" v-if="movies.length > 0">
      <v-col cols="12" class="text-center">
        <v-pagination
          v-model="currentPage"
          :length="totalPages"
          :total-visible="7"
          color="primary"
        ></v-pagination>
      </v-col>
      <v-col cols="12" class="text-center grey--text">
        共 {{ totalMovies }} 部电影
      </v-col>
    </v-row>

    <v-row justify="center" v-if="movies.length === 0">
      <v-col cols="12" class="text-center">
        <v-alert
          type="info"
          text
          prominent
        >
          暂无电影数据
        </v-alert>
      </v-col>
    </v-row>
  </div>
</template>

<script>
import MovieCard from "../components/MovieCard";
import {get} from "../api/movie";

export default {
  components: {MovieCard},
  name: "Home",
  data: () => ({
    movies: [],
    currentPage: 1,
    itemsPerPage: 12,
    totalMovies: 0,
    searchQuery: '',
    searching: false,
    selectedCategory: '全部',
    sortBy: '评分从高到低',
    categories: [
      '全部',
      '剧情',
      '喜剧',
      '动作',
      '爱情',
      '科幻',
      '冒险',
      '动画',
      '悬疑',
      '惊悚',
      '犯罪',
      '奇幻',
      '战争',
      '历史'
    ],
    sortOptions: [
      '评分从高到低',
      '评分从低到高',
      '上映时间最新',
      '上映时间最早'
    ]
  }),
  computed: {
    filteredMovies() {
      let result = [...this.movies];
      
      // 应用类别筛选
      if (this.selectedCategory !== '全部') {
        result = result.filter(movie => 
          movie.genres && movie.genres.includes(this.selectedCategory)
        );
      }
      
      // 应用排序
      switch(this.sortBy) {
        case '评分从高到低':
          result.sort((a, b) => b.douban_score - a.douban_score);
          break;
        case '评分从低到高':
          result.sort((a, b) => a.douban_score - b.douban_score);
          break;
        case '上映时间最新':
          result.sort((a, b) => b.year - a.year);
          break;
        case '上映时间最早':
          result.sort((a, b) => a.year - b.year);
          break;
      }
      
      return result;
    },
    paginatedMovies() {
      const start = (this.currentPage - 1) * this.itemsPerPage;
      const end = start + this.itemsPerPage;
      return this.filteredMovies.slice(start, end);
    },
    totalPages() {
      return Math.ceil(this.filteredMovies.length / this.itemsPerPage);
    }
  },
  watch: {
    selectedCategory() {
      this.currentPage = 1;
    },
    sortBy() {
      this.currentPage = 1;
    }
  },
  async mounted() {
    try {
      const res = await get({"keyword": ''});
      if (res.data && res.data.data) {
        this.movies = res.data.data.movies || res.data.data;
        this.totalMovies = res.data.data.total || this.movies.length;
      }
      console.log('Movies loaded:', this.movies); // 添加调试日志
    } catch (error) {
      console.error('Failed to load movies:', error);
    }
  },
  methods: {
    async handleSearch() {
      this.searching = true;
      try {
        const res = await get({ keyword: this.searchQuery || '' });
        if (res.data && res.data.data) {
            this.movies = res.data.data.movies || [];
            this.totalMovies = res.data.data.total || this.movies.length;
        } else {
            this.movies = [];
            this.totalMovies = 0;
        }
        this.currentPage = 1;
      } catch (error) {
        console.error('搜索失败:', error);
        this.movies = [];
        this.totalMovies = 0;
      } finally {
        this.searching = false;
      }
    },
  }
}
</script>

<style scoped>
.home {
  padding-bottom: 40px;
}

/* 在大屏幕上优化布局 */
@media (min-width: 1264px) {
  .movie-col {
    flex: 0 0 25% !important;
    max-width: 25% !important;
  }
}
</style>
